package Sparse_Arrays_01;

/*
 * @Author 罗
 * @date 2020/3/10 - 9:10 下午
 *
 */

import Sparse_Arrays_01.Entity.ChestData;
import Sparse_Arrays_01.Entity.FieldMapping;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.lang.reflect.Field;

public class CreateXmlFile {
public static final String XML_FILE_PATH = "/Users/luo/Desktop/chess.xml";

    public void createXml(ChestData[] parse){

        Document document = DocumentHelper.createDocument();

        Element rootElement = document.addElement("ParseArray");
//        获取反射
        Class parseChest = parse[0].getClass();

//        获取属性
        Field[] fields =  parseChest.getDeclaredFields();

        for (int i = 0; i < parse.length; i++) {

            Element chessElement = rootElement.addElement("chess");
            for (Field field : fields) {
                field.setAccessible(true);
                //            根据属性获取注解，再添加节点
                Element sonElement = chessElement.addElement( field.getAnnotation(FieldMapping.class).name() );
//                通过反射获取该属性的值，再写入该节点
                try {
                    sonElement.addText(field.get(parse[i]).toString());
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
//        美化存储
        Writer writer = null;
        try {
            writer = new OutputStreamWriter(new FileOutputStream(XML_FILE_PATH));
            OutputFormat format = OutputFormat.createPrettyPrint();
            XMLWriter xmlWriter = new XMLWriter(writer,format);
            xmlWriter.write(document);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }
}
